const list = [
    { id: 1, pid: 0 },
    { id: 2, pid: 0 },
    { id: 3, pid: 0 },
    { id: 11, pid: 1 },
    { id: 12, pid: 1 },
    { id: 13, pid: 1 },
    { id: 21, pid: 2 },
    { id: 22, pid: 2 },
    { id: 23, pid: 2 },
    { id: 31, pid: 3 },
    { id: 32, pid: 3 },
    { id: 33, pid: 3 },
    { id: 111, pid: 11 },
    { id: 221, pid: 22 },
    { id: 331, pid: 33 },
    { id: 3331, pid: 331 }
]


const listToTree = (list) => {
    let arr = [];
    let temp = {};
    for (const item of list) {
        Reflect.set(temp, item.id, item);
    }
    console.log(temp)
    for (const id of Object.keys(temp)) {
        if (temp[id]['pid'] !== 0) {
            temp[temp[id]['pid']].children || (temp[temp[id]['pid']].children = []);
            temp[temp[id]['pid']].children.push(temp[id]);
        } else {
            arr.push(temp[id]);
        }
    }
    return arr;
}
const arr = listToTree(list);
console.log(arr)
